using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace Microsoft.WowAddonStudio.FrameXml.Design.Services.NameCreationService
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class ContinualUniqueNumberGenerator : UniqueNumberGeneratorBase
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="ContinualUniqueNumberGenerator"/> class.
		/// </summary>
		/// <param name="componentContainer">The component container.</param>
		public ContinualUniqueNumberGenerator(IContainer componentContainer)
			: base(componentContainer)
		{
		}

		#region IUniqueNumberGenerator Members

		/// <summary>
		/// Generates the unique number.
		/// </summary>
		/// <param name="prefixName">Name of the prefix.</param>
		/// <returns></returns>
		public override int GenerateUniqueNumber(string prefixName)
		{
			int result = 1;
			if (ComponentContainer != null)
			{
				List<Component> controls = GetComponents(prefixName);
				if (controls.Count > 0)
				{
					var numbers = new List<int>(controls.Count);
					controls.ForEach(ctrl =>
					                 	{
					                 		int num = GetNumericChars(ctrl.Site.Name.Replace(prefixName, String.Empty));
					                 		numbers.Add(num);
					                 	});
					numbers.Sort();
					for (int index = 0; index < numbers.Count; index++)
					{
						int number = numbers[index];
						if (index + 1 < numbers.Count)
						{
							if (numbers[index + 1] != number + 1)
							{
								result = number + 1;
								break;
							}
						}
						else
						{
							result = numbers[numbers.Count - 1] + 1;
							break;
						}
					}
				}
			}
			return result;
		}

		#endregion
	}
}